import urequests as requests
import json
import time
import network
import gc
from machine import UART, Pin
from oled import OLED

# 初始化WiFi连接
def init_wifi():
    # 从配置文件读取WiFi信息
    try:
        with open('config.json', 'r') as f:
            config = json.load(f)
            wifi_ssid = config.get('wifi_ssid')
            wifi_password = config.get('wifi_password')
    except:
        print('无法读取WiFi配置，请检查config.json文件')
        return

    if not wifi_ssid or not wifi_password:
        print('WiFi配置信息不完整，请检查config.json文件')
        return

    # 初始化WiFi连接
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    if not wlan.isconnected():
        print('连接到WiFi...')
        wlan.connect(wifi_ssid, wifi_password)
        while not wlan.isconnected():
            pass
    print('WiFi已连接')
    print('网络配置:', wlan.ifconfig())

# 从配置文件读取API密钥
def load_config():
    try:
        with open('config.json', 'r') as f:
            config = json.load(f)
            return config['api_key'], config['api_endpoint']
    except:
        return None, None

# DeepSeek API配置
API_KEY, API_ENDPOINT = load_config()
if not API_KEY or not API_ENDPOINT:
    API_KEY = "sk-3b5d049ffacd4846a3120698cbd2dbe3"  # 默认API密钥
    API_ENDPOINT = "https://api.deepseek.com/v1/chat/completions"  # 默认API端点

# 初始化OLED显示屏
oled = OLED()

# 初始化串口用于语音识别
uart = UART(1, baudrate=115200)

def send_to_deepseek(text):
    """发送文本到DeepSeek API并获取响应"""
    # 执行垃圾回收
    gc.collect()
    
    headers = {
        "Authorization": f"Bearer {API_KEY}",
        "Content-Type": "application/json"
    }
    
    data = {
        "model": "deepseek-chat",
        "messages": [{"role": "user", "content": text}]
    }
    
    try:
        response = requests.post(API_ENDPOINT, headers=headers, json=data)
        if response.status_code == 200:
            result = response.json()
            response.close()  # 释放连接资源
            return result['choices'][0]['message']['content']
        else:
            response.close()  # 释放连接资源
            return f"错误: {response.status_code}"
    except Exception as e:
        return f"请求失败: {str(e)}"
    finally:
        gc.collect()  # 再次执行垃圾回收

def display_text(text):
    """在OLED屏幕上显示文本"""
    oled.clear()
    # 将长文本分成多行显示
    lines = [text[i:i+16] for i in range(0, len(text), 16)]  # 假设OLED每行16字符
    for i, line in enumerate(lines[:4]):  # 显示前4行
        oled.show_str(0, i*16, line)
    oled.refresh()

def main():
    print("初始化WiFi连接...")
    init_wifi()
    
    print("开始运行DeepSeek API交互程序...")
    oled.clear()
    oled.show_str(0, 0, "等待语音输入...")
    oled.refresh()
    
    while True:
        if uart.any():
            # 读取语音识别结果
            text = uart.read().decode('utf-8').strip()
            if text:
                print(f"识别到语音输入: {text}")
                display_text("正在处理...")
                
                # 发送到DeepSeek API
                response = send_to_deepseek(text)
                print(f"DeepSeek响应: {response}")
                
                # 显示响应
                display_text(response)
        
        time.sleep(0.1)

if __name__ == "__main__":
    main()